package com.ordersys.cloud.controller;
import com.ordersys.cloud.domain.R;
import com.ordersys.cloud.entity.Product;
import com.ordersys.cloud.entity.ProductDTO;
import com.ordersys.cloud.enums.ReturnCodeEnum;
import com.ordersys.cloud.service.ProductService;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Resource
    ProductService productService;

    @PostMapping(value = "/add")
    public R<String> addProduct(@RequestBody Product product){
        System.out.println(product.toString());
        int i = productService.addProduct(product);
        return R.ok("成功插入记录，返回值："+i);
        //return "成功插入记录，返回值："+i;
    }

    @GetMapping(value = "/del/{id}")
    public R deleteProduct(@PathVariable("id") Integer id) {
        int i = productService.deleteProduct(id);
        if (i==1){
            return R.ok("删除成功");
        }else {
            return R.fail(ReturnCodeEnum.RC88.getCode(),"删除失败");
        }

        //return payService.deletePay(id);
    }

    @PostMapping(value = "/update")
    public R<String> updateProduct(@RequestBody ProductDTO productDTO){
        Product product = new Product();
        BeanUtils.copyProperties(productDTO, product);

        int i = productService.updateProduct(product);
        if (i>=1){
            return R.ok("成功修改记录，返回值："+i);
        }else {
          return  R.ok("没有插入数据","插入"+i);
        }

    }


    @GetMapping(value = "/getProductById/{id}")
    public R<Product> getProductById(@PathVariable("id") Integer id){
        if(id == -1) throw new RuntimeException("id不能为负数");
//        try {
//            //模拟超时。服务提供方业务处理,为了测试feign的超时时间控制，设置线程睡眠62秒
//            Thread.sleep(62*1000);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        Product product = productService.getProductById(id);
        if (product!=null){
            return R.ok(product,"查找成功");
        }else {
            //空
            return R.fail(product,"商品不存在");
        }

    }


    @GetMapping("/getProductAllList")
    public R<List<Product>> getProductAllList(){
        List<Product> payAllList = productService.getProductAllList();
        return R.ok(payAllList);
    }


    //减库存
    @PostMapping(value = "/{productId}/reduceStock")
    public Integer reduceStock(@PathVariable("productId") Integer productId,@RequestParam("quantity") Integer quantity){
        Integer i = productService.reduceStock(productId, quantity);
        return i;
    }


}
